package logic

import (
	"context"
	"encoding/json"

	"dfx_cmdb/cmdb-account-management-rpc/internal/svc"
	cmdb_account_management_rpc "dfx_cmdb/cmdb-account-management-rpc/types/cmdb-account-management-rpc"
	cmdbaccountmanagement "dfx_cmdb/models/cmdb-account-management"

	toolsdatabase "gitee.com/daofeixian/dfx_golang_toolset/databases"
	"github.com/zeromicro/go-zero/core/logx"
)

type QueryAccountInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewQueryAccountInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *QueryAccountInfoLogic {
	return &QueryAccountInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *QueryAccountInfoLogic) QueryAccountInfo(in *cmdb_account_management_rpc.QueryAccountInfoRequest) (*cmdb_account_management_rpc.QueryAccountInfoResponse, error) {
	conditions := make([]toolsdatabase.QueryCondition, 0)
	for _, condition := range in.QueryCondition {
		if condition.Field == "" || condition.Value == "" {
			continue
		}
		conditions = append(conditions, toolsdatabase.QueryCondition{
			Field: condition.Field,
			Value: condition.Value,
			Op:    condition.Op,
		})
	}

	query := &toolsdatabase.QueryInfo{
		Limit:           in.Limit,
		Page:            in.Page,
		QueryConditions: conditions,
	}
	accounts := make([]cmdbaccountmanagement.AccountManagement, 0)
	err := toolsdatabase.AdvancedQueryDatabase[cmdbaccountmanagement.AccountManagement](l.ctx, l.svcCtx.PDB, &accounts, *query)
	if err != nil {
		logx.Errorf("查询账号信息失败: %v", err)
		return nil, err
	}
	// 转换为响应对象
	result := make([]*cmdb_account_management_rpc.UpdateAccessInfoRequest, 0, len(accounts))
	for _, account := range accounts {
		// 将 JSON 类型的 OtherInfo 转换为 map[string]string
		otherInfoMap := make(map[string]string)
		if len(account.OtherInfo) > 0 {
			// 尝试解析 JSON
			var tempMap map[string]interface{}
			if err := json.Unmarshal(account.OtherInfo, &tempMap); err == nil {
				// 将 interface{} 转换为 string
				for k, v := range tempMap {
					if strVal, ok := v.(string); ok {
						otherInfoMap[k] = strVal
					} else {
						// 如果不是字符串，转换为 JSON 字符串
						if jsonBytes, err := json.Marshal(v); err == nil {
							otherInfoMap[k] = string(jsonBytes)
						}
					}
				}
			}
		}

		result = append(result, &cmdb_account_management_rpc.UpdateAccessInfoRequest{
			Id:           int32(account.ID),
			Type:         account.Type,
			Platform:     account.Platform,
			PlatformName: account.PlatformName,
			Account:      account.Account,
			Password:     account.Password,
			Token:        account.Token,
			Accesskey:    account.Accesskey,
			Accesssecret: account.Accesssecret,
			Comment:      account.Comment,
			OtherInfo:    otherInfoMap,
		})
	}
	total := len(accounts)

	logx.Infof("查询账号信息成功，总数: %d, 当前页: %d, 每页: %d, 返回: %d 条", total, query.Page, query.Limit, len(result))

	return &cmdb_account_management_rpc.QueryAccountInfoResponse{
		UpdateAccessInfoRequest: result,
	}, nil
}
